package com.aaa.controller;

import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("fileupload")
public class CommonResult {
    @RequestMapping("upload")
    @ResponseBody
    public String upload(MultipartFile photo) throws IOException {
        System.out.println(photo); // 表单提交的 name="photo"
        String name = photo.getName();
        System.out.println("name:" + name);
        Resource resource = photo.getResource();
        System.out.println(resource);
        // getOriginalFilename:获取文件原名，上传的文件名
        String originalFilename = photo.getOriginalFilename();
        System.out.println("originalFilename:" + originalFilename);
        // getSize:文件大小，字节数
        long size = photo.getSize();
        System.out.println("size:" + size); // 文件字节内容

        byte[] bytes = photo.getBytes();
        System.out.println("bytes:" + bytes.toString());
        // getContentType:上传文件的类型，application/vnd.ms-excel，
        // image/png， image/x-icon
         String contentType = photo.getContentType();
         System.out.println("contentType:" + contentType);
         // 保存文件
        // 1.判断是否有上传的文件；
        // 不存在一个文件没有文件名
         if (!"".equals(originalFilename)) {
             System.out.println("选择了上传的文件");
             // 2.文件保存的名字,不能重复,重名的文件会被覆盖
             String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
             // 3.文件保存的路径 D:/photos
             String filePath = "D:/photos/" + fileName;
             // 4.存文件
              photo.transferTo(new File(filePath));
         }return "ok";
    }

}



